package com.copro.chemdb.stat.rule.export;

import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.stat.ExportRule;
import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;

public class Rule2 implements ExportRule {

	@SuppressWarnings("unchecked")
	@Override
	public void doExport(HSSFWorkbook wb, Subject subject, StatResult re,
			short customStyle, Application app) throws SimpleException {
		Map<String, Object> result = (Map<String, Object>) re.getResult();
		String text = (String) result.get("text");
		if (text.length() > 30) {
			text = text.substring(0, 30);
		}
		// create new sheet
		HSSFSheet sheet = wb.createSheet(text);
		HSSFRow row = sheet.createRow(0);
		// set the header
		CellUtil.createCell(row, 0, "", wb
				.getCellStyleAt((short) (customStyle + StyleHeader)));
		List<String> headers = (List<String>) result.get("areaTitles");
		for (int i = 0; i < headers.size(); i++) {
			CellUtil.createCell(row, i + 1, headers.get(i), wb
					.getCellStyleAt((short) (customStyle + StyleHeader)));
		}
		// set the datas
		int count = 0;
		List<Integer> values = (List<Integer>) result.get("areaValues");
		row = sheet.createRow(1);
		CellUtil.createCell(row, 0, "数量");
		for (int i = 0; i < values.size(); i++) {
			CellUtil.createCell(row, i + 1, values.get(i).intValue(), wb
					.getCellStyleAt((short) (customStyle + StyleInt)));
			count += values.get(i).intValue();
		}
		row = sheet.createRow(2);
		CellUtil.createCell(row, 0, "所占比例");
		double percent = 0;
		for (int i = 0; i < values.size(); i++) {
			percent = count == 0 ? 0 : values.get(i).doubleValue() / count;
			CellUtil.createCell(row, i + 1, percent, wb
					.getCellStyleAt((short) (customStyle + StylePercent)));
		}
	}

	@Override
	public void setup(Properties conf) {
	}

}
